#include "mysqlx_opt.h"
#include <iostream>

mysqlx_opt::mysqlx_opt(const std::string& ip, ushort port, const std::string& name,
    const std::string& pwd, const std::string& dbname)
{
    mysqlx::SessionSettings s(
        mysqlx::SessionOption::USER, name,
        mysqlx::SessionOption::PWD,  pwd,
        mysqlx::SessionOption::HOST, ip,
        mysqlx::SessionOption::PORT, port,
        mysqlx::SessionOption::DB,   dbname
        // SessionOption::SSL_MODE, SSLMode::DISABLED
    );
        // s.set(SessionOption::AUTH, AuthMethod::MYSQL41);
    try{
        _session = std::make_shared<mysqlx::Session>(s);
    }
    catch (const mysqlx::Error &err)
    { std::cout << "mysql EXCEPTION:" << err << std::endl; }
    catch (std::exception &ex)
    { std::cout <<"STD EXCEPTION: " << ex.what() << std::endl; }
    catch (const char *ex)
    { std::cout <<"EXCEPTION: " << ex << std::endl; }
    catch (...) { std::cout << "UNKNOW EXCEPTION!" << std::endl; }
    
    if(connected())
        std::cout << "mysqlx_opt has connected!" << std::endl;
}
mysqlx::SqlResult mysqlx_opt::execute(const std::string& sql)
{
    std::lock_guard<std::mutex> lock(_mutex);
    mysqlx::SqlResult r;
    if(!connected())
        return r;

    try
    {
        r = _session->sql(sql).execute();
    }
    catch (const mysqlx::Error &err)
    {
        std::cout <<"ERROR: " <<err <<std::endl;
        // return 1;
    }
    catch (std::exception &ex)
    {
        std::cout <<"STD EXCEPTION: " <<ex.what() <<std::endl;
        // return 1;
    }
    catch (const char *ex)
    {
        std::cout <<"EXCEPTION: " <<ex <<std::endl;
        // return 1;
    }

    return r;
}